package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //  进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝，比一个一个set更快捷。
        //前提是对象属性名一致
        BeanUtils.copyProperties(employeeDTO, employee);
        //其他属性设置
        //设置状态为启用，1为启用，0为禁用，设置了一个常量类StatusConstant表示状态
        employee.setStatus(StatusConstant.ENABLE);
        //设置默认密码123456，加密后保存到数据库，密码加密算法为md5，常量类PasswordConstant表示默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        /**
         * 后面设置了自动填充，不需要手动设置，所以注释掉了
         */
        //设置创建时间，修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //记录创建人和修改人id
        //这里需要注意，如果当前线程没有登录，则会报错，所以需要先登录，或者在调用处设置BaseContext.setCurrentId()
        //利用threadlocal来获取当前线程的id
        //BaseContext.getCurrentId()获取当前登录用户id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //保存到数据库
        employeeMapper.insert(employee);
    }

    /**
     * 分页查询员工
     *
     * @param employeePageQueryDTO
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //sql分页查询 selecr * from employee limit 0,10;
        //limit 0,10 表示从0开始，查询10条记录
        //分页查询需要返回总记录数、当前页数据、分页信息
        //插件PageHelper可以自动处理分页查询，不需要自己写sql分页语句
        //底层原理还是在数据库查询语句拼接上limit语句
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //调用mapper查询方法
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        long total = page.getTotal();
        List<Employee> records = page.getResult();

        //封装分页结果
        return new PageResult(total, records);
    }

    /**
     * 更新员工状态：启用/停用
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //根据id更新员工状态
        //update employee set status = ？ where id = ？;

//        Employee employee= new Employee();
//        employee.setStatus(status);
//        employee.setId(id);

        Employee employee = Employee.builder()
                .status(status)
                .id(id)
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
                .build();
        //要动态更新
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        //为了安全起见，密码不返回给前端
        employee.setPassword(null);
        return employee;
    }

    /**
     * 编辑员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝，比一个一个set更快捷。
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置修改时间
//        employee.setUpdateTime(LocalDateTime.now());
        //记录修改人id
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //更新到数据库
        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        Employee employee = new Employee();
        //获取当前登录用户id
        //利用threadlocal来获取当前线程的id
        //BaseContext.getCurrentId()获取当前登录用户id
        Long id = BaseContext.getCurrentId();

        //核算旧密码是否正确
        String oldPassword = passwordEditDTO.getOldPassword();
        String nowPassword = employeeMapper.getPasswordById(id);

        //进行md5加密，然后再进行比对
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!oldPassword.equals(nowPassword)) {
            //密码错误，抛出异常
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //密码加密算法为md5
        String password = passwordEditDTO.getNewPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //更新数据
        employee.setId(id);
        employee.setPassword(password);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //更新到数据库
        employeeMapper.update(employee);
    }
}